package com.qqt.csr.order.service.statemachine.action.impl;

import com.google.common.collect.Lists;
import com.qqt.csr.message.event.intrasite.IntraSiteMessageEventPublisher;
import com.qqt.csr.message.event.intrasite.workorder.WorkOrderEventSource;
import com.qqt.csr.order.entity.WorkOrder;
import com.qqt.csr.order.enums.WorkOrderEventEnum;
import com.qqt.csr.order.enums.WorkOrderStatusEnum;
import com.qqt.csr.order.enums.WorkOrderTemplateType;
import com.qqt.csr.order.service.event.DynamicEvent;
import com.qqt.csr.order.service.event.DynamicEventListener;
import com.qqt.csr.order.service.event.DynamicEventSource;
import com.qqt.csr.order.service.statemachine.action.IActionPostProcessor;
import com.qqt.csr.order.service.statemachine.action.IActionPreProcessor;
import com.qqt.csr.order.service.statemachine.context.WorkOrderContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ReceivedWorkOrderProcessor extends AbstractWorkOrderProcessor implements IActionPostProcessor {
    @Autowired
    private IntraSiteMessageEventPublisher messageEventPublisher;
    @Autowired
    private DynamicEventListener dynamicEventListener;

    @Override
    public boolean matches(WorkOrderEventEnum event) {
        return WorkOrderEventEnum.RECEIVED.equals(event);
    }

    @Override
    public void postProcess(WorkOrderStatusEnum from, WorkOrderStatusEnum to, WorkOrderEventEnum event, WorkOrderContext context) {
        WorkOrder toOrder = context.getToOrder();
        WorkOrder fromOrder = context.getFromOrder();
        if (fromOrder.isNeedSysNotify() && !fromOrder.getCreatorId().equals(toOrder.getDesigneeId())) {
            // 推送认领通知到创建人
            WorkOrderEventSource workOrderEventSource = new WorkOrderEventSource()
                    .setWorkOrderId(fromOrder.getId())
                    .setWorkOrderName(fromOrder.getTitle())
                    .setEventType(WorkOrderTemplateType.RECEIVED_WORK_ORDER)
                    .setParams(new String[]{context.getOperatorName()})
                    .setExt("{\"permission\":\""+ORDER_CREATOR_PERM+"\"}")
                    .setRecipientIds(Lists.newArrayList(fromOrder.getCreatorId()));
            messageEventPublisher.publishEvent(workOrderEventSource);
        }

        recordDynamic(context, event);
    }

    /**
     * 记录动态
     *
     * @param context
     */
    private void recordDynamic(WorkOrderContext context, WorkOrderEventEnum event) {
        DynamicEventSource eventSource = new DynamicEventSource()
                .setEvent(event)
                .setOrderId(context.getToOrder().getId());
        dynamicEventListener.onApplicationEvent(new DynamicEvent(eventSource));
    }

}
